<template>
	<rootWithStateBarLayout :rightToolBarData="toolDataList" @onToolItemClick="onToolItemClick"
		:rightToolBarBgColor="toolBarBgColor">

		<view slot="pageContent" class="content-lay flex-v">
			<view class="header flex-h">
				<view class="flex-h" style="align-items: center">
					<image @click="navigateBack" class="back-image" src="/static/imgs/tools/icon_nav_back_dark@2x.png">
					</image>

					<view class="header-name-lay flex-h">
						<text class="header-name">{{$t("thickShow.macTypeStr")}}：</text>
						<text
							class="header-value header-value-oth">{{selectTableData ? selectTableData.mac_numb : '--'}}</text>
					</view>

					<view class="header-name-lay flex-h">
						<text class="header-name">{{$t('thickShow.pointNo')}}：</text>
						<text class="header-value">{{ tableSelectData ? tableSelectData.pos_no : '--' }}</text>
					</view>

					<view class="header-name-lay flex-h">
						<text class="header-name">{{$t('thickShow.macSum')}}：{{ getHeaderSum }}</text>
					</view>
				</view>
				<image @click="onResetViewClick" style="width: 32rpx; height: 32rpx;"
					src="/static/imgs/tools/icon_menu_initial_state@2x.png"></image>
			</view>
 			<view class="work-lay flex-h">
				<view class="left-info-lay">
					<drawInfoView v-if="showState == 'table'" :infoData="infoTableData" :valueData="tableSelectData"
						:pointData="tableDataList" :hisData="hisData"
						:planImplementationData="planImplementationData" />
					<photoListView ref="photoListView" v-if="showState != 'table'" class="photo-list"
						:photoList="takePhotoPaths" />
				</view>

				<view class="right-content-lay">
					<drawingBasicFun ref="drawingBasicFun" class="draw-content" :ballMarkData="showDrawBallData"
						:svgOption="svgOption" , :selectedMarkupId="tableSelectData ? tableSelectData.pos_no : 0" ,
						@onMarkupSelected="onElementSelect" :needScreenShot="true" @onDrawShotFinish="onDrawShotFinish"
						:style="' height: ' + (showState == 'table' ? '70%' : '100%')" />
					<checkInfoTableView ref="checkInfoTableView" v-if="showState == 'table'" class="check-table"
						:headData="tableHeadData" :contentData="tableDataList" :tableHeight="tableHeight"
						@onSelectionChange="onTableSelectionChange" />
				</view>
			
			</view>

<!-- 			<view style="position: absolute; left: 0; bottom: 0;">
				<image style="width: 200rpx; height: 200rpx;" :src="drawShotPath"></image>
			</view> -->
		</view>
		<view slot="popupContent">
			<hqs-popup title="弹窗标题" v-model="showWildAccountPopup" from="right" width="60vw">
				<wildAccountView @closePopup="closeWildAccountView" :drawShotPath="drawShotPath"
					:dmgCode="selectTableData ? selectTableData.dmg_code : 0"></wildAccountView>
			</hqs-popup>

			<hqs-popup title="弹窗标题" v-model="showLogPopup" from="right" width="464upx" class="hqs-popup">
				<logView :posNo="tableSelectData?tableSelectData.pos_no:0" @closePopup="closelogView"></logView>
			</hqs-popup>
		</view>
	</rootWithStateBarLayout>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";

	import {
		genLocalDrawPath
	} from "@/localService/index.js";

	import {
		requireMarkupBallData
	} from "@/localService/markupService.js";

	import {
		requireThickDetailData,
		requireThickHistoryData,
		requireThickImplementationData,
		updateThickListPlanState
	} from "@/localService/thickService.js";

	import {
		requireThickPhotoByMacnumbAndPosno,
		addThickPhotoByMacnumbAndPosno
	} from "@/localService/thickPhotoService.js";

	import selectData from "@/common/thick_show_data.js";
	import drawingBasicFun from "@/_components/drawing/drawingBasicFun.vue";
	import drawInfoView from "./_components/drawInfoView.vue";
	import checkInfoTableView from "./_components/checkInfoTableView.vue";
	import wildAccountView from "./_components/wildAccountView.vue";
	import logView from "./_components/logView.vue";
	import photoListView from "./_components/photoListView.vue";

	import hqsPopup from "@/components/hqs-popup/hqs-popup";

	import rootWithStateBarLayout from "@/_components/rootWithStateBarLayout.vue";
	import testBallMarkData from "@/common/test_ball.js"
	export default {
		components: {
			drawingBasicFun,
			drawInfoView,
			checkInfoTableView,
			hqsPopup,
			wildAccountView,
			logView,
			photoListView,
			rootWithStateBarLayout,
		},

		beforeDestroy() {
			console.log("beforeDestroy====")
			plus.io.resolveLocalFileSystemURL(this.drawShotPath, function(entry) {
				// 可通过entry对象操作test.html文件 
				entry.file(function(file) {
					if (file.isFile())
						file.remove();
				});
			}, function(e) {
				alert("Resolve file URL failed: " + e.message);
			});
		},

		onReady() {
			this.selectTableData = getApp().globalData.selectListItemData;
			let _this = this;
			let view = uni.createSelectorQuery().in(this).select(".work-lay");
			view
				.fields({
						size: true, //是否返回节点尺寸（width height）
						rect: true, //是否返回节点的 scrollLeft scrollTop，节点必须是 scroll-view 或者 viewport
						scrollOffset: true, //是否返回节点的 scrollLeft scrollTop，节点必须是 scroll-view 或者 viewport
					},
					(res) => {
						console.log("------------0-0-0-0-0-     " , res )
						_this.workLayHeight =
							uni.getSystemInfoSync().windowHeight - res.top - 30 + "rpx";
						_this.tableHeight =
							(res.height * 0.3) - 32;
							console.log("------------0-0-0-0-0-  _this.tableHeight   " ,_this.tableHeight )
					}
				)
				.exec();

			this.selectTableData = getApp().globalData.selectListItemData;
			let _self = this;

			/**
			 * 获取图纸本地地址
			 */
			genLocalDrawPath(this.selectTableData.drw_pass, this.selectTableData.plt_path).then(e => {
				this.$nextTick(function() {
					_self.svgOption.svgSourcePath = e;
					_self.svgOption.svgSourceUrl = e;
				})
			});

			this.initOptData();
			this.requireThickImplementationDataApi([1, 2, 3], this.selectInfo.macType);
			this.requireMarkupBallDataApi(this.selectTableData.dmg_code);
			this.requireThickDetailDataApi(this.selectTableData.dmg_code);
		},

		data() {
			return {
				/**
				 * 前个页面选中的列表项
				 */
				selectTableData: null,
				selectPosNo: -1,

				/**
				 * 图纸地址
				 */
				svgOption: {
					svgSourcePath: "",
					svgSourceUrl: "",
				},

				toolDataList: selectData.toolEntry,
				toolBarBgColor: "#FF8D8E",

				showDrawBallData: [],
				drawShotPath: '', // svg截图
				// 图上选择的球标
				// drawSelectData: null,

				showState: "table", // photo

				infoTableData: selectData.tableInfoData,
				tableHeadData: [],
				tableDataList: [],
				tableHeight: 0,
				// 表格上选择的球标
				tableSelectData: null,
				tableShowType: 0, // 0 1 2  三种显示方式  对应 ShowType

				showWildAccountPopup: false, // 野账弹出窗
				showLogPopup: false,

				takePhotoPaths: [],

				// 左上角表格二
				hisData: [],
				// 左边检查进度图表
				planImplementationData: [],
			};
		},

		computed: {
			...mapState(["userInfo", "selectInfo"]),

			getHeaderSum() {
				let reSum = 0;
				let tempLastPosOrdr = -1;
				this.tableDataList.forEach(e => {
					if (e.pos_ordr != tempLastPosOrdr) {
						reSum++;
						tempLastPosOrdr = e.pos_ordr;
					}
				})
				return reSum;
			}
		},

		onShow() {
			if (this.selectPosNo != -1)
				this.requireThickPhotoByMacnumbAndPosnoApi(this.selectTableData.mac_numb, this.selectPosNo);
		},

		methods: {
			initOptData() {
				let _self = this;
				selectData.checkTableData.headData.forEach(e => {
					e.title = _self.$t(e.titleT);
				})
				// this.tableHeadData = selectData.checkTableData.headData;
				this.updateTableShowType();
			},

			/**
			 * 查找图纸的球标，并显示 根据图纸的dmgcode查询
			 * @param {Object} inDmgCode
			 */
			requireMarkupBallDataApi(inDmgCode) {
				let _self = this;
				requireMarkupBallData(inDmgCode).then(originData => {
					let reList = [];
					for (let i = 0; i < originData.length; i++) {
						let originItem = originData[i];
						let reListLength = reList.length;
						let reListLastItem = reListLength > 0 ? reList[reListLength - 1] : null;

						// 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同 										
						if (reListLength == 0 ||
							reListLastItem.pos_no != originItem.pos_no ||
							(reListLastItem.pos_no == originItem.pos_no &&
								reListLastItem.bln_kbn != originItem.bln_kbn)) {

							let ballTemp = {};
							ballTemp.sId = originItem.pos_no;
							ballTemp.shapeType = Number(originItem.bln_type) + 12;
							ballTemp.showType = "trans";
							ballTemp.showID = originItem.pos_no;
							ballTemp.lineColor = "#0000ff";
							ballTemp.lineWidth = "5";
							ballTemp.fontSize = originItem.bln_fntsiz;
							ballTemp.fontName = originItem.bln_fntnam;
							ballTemp.lineStyle = "0";
							ballTemp.points = [];
							ballTemp.bln_kbn = originItem.bln_kbn;
							ballTemp.pos_no = originItem.pos_no;
							ballTemp.posOrder = originItem.pos_no;

							ballTemp.points.push({
								bln_x: originItem.bln_x,
								bln_y: originItem.bln_y,
								x: originItem.bln_x,
								y: originItem.bln_y,
							})

							reList.push(ballTemp);
						} else {
							reListLastItem.points.push({
								bln_x: originItem.bln_x,
								bln_y: originItem.bln_y,
								x: originItem.bln_x,
								y: originItem.bln_y,
							})
						}
					}
					_self.showDrawBallData = reList;
				})
			},

			/**
			 * 查找图纸的表格信息
			 * @param {Object} inDmgCode
			 */
			requireThickDetailDataApi(inDmgCode) {
				let _self = this;
				requireThickDetailData(inDmgCode).then(dataList => {
					console.log("===========requireThickDetailDataApi --- res ===========")
					console.log(dataList)

					for (let i = 0; i < dataList.length; i++) {
						dataList[i].index = i + 1;
						dataList[i].id = "thickShowTable-" + i;

						dataList[i].planSign = dataList[i].plan_cls_type == 3 ? '●' : (dataList[i].plan_cls_type ==
							2 ? '●' : (dataList[i].plan_cls_type == 1 ? '○' : ''));
					}
					this.tableDataList = dataList;
					
					this.checkUpdateThickPlanState();
				})
			},

			/**
			 * 查询检查点检查历史记录
			 */
			requireThickHistoryDataApi() {
				let _self = this;
				requireThickHistoryData(this.tableSelectData.dmg_code,
					this.tableSelectData.pos_no,
					this.tableSelectData.cls_type,
					this.tableSelectData.plt_name).then(data => {
					console.log(data);
					if (!data || data.length == 0)
						return;

					let tempGroups = new Array();
					tempGroups = data[0].hist.split(",");

					let reArray = [];
					tempGroups.forEach(e => {
						let temp = {};
						let tempSub = e.split(":");
						temp.key = tempSub[0];
						temp.value = tempSub[1];
						reArray.push(temp);
					})
					this.hisData = reArray;
				})
			},

			/**
			 * 查询计划状态
			 * @param {Object} inStateArray
			 */
			requireThickImplementationDataApi(inStateArray, inMacType) {
				requireThickImplementationData(inStateArray, inMacType).then(e => {
					this.planImplementationData = e;
				})
			},

			/**
			 * 查询检查点的照片和备注
			 * @param {Object} inMacNumb
			 * @param {Object} inPosNo
			 */
			requireThickPhotoByMacnumbAndPosnoApi(inMacNumb, inPosNo) {
				requireThickPhotoByMacnumbAndPosno(inMacNumb, inPosNo).then(e => {
					this.takePhotoPaths = e;
				})
			},

			addThickPhotoByMacnumbAndPosnoApi(inPath) {
				let _self = this;
				addThickPhotoByMacnumbAndPosno({
					file: inPath,
					photo_memo: "default memo",
					not_print: 0,
					mac_numb: _self.selectTableData.mac_numb,
					pos_no: _self.selectPosNo,
					photo_type: 1,
					plt_name: _self.selectTableData.plt_name,
					mac_type: _self.selectTableData.mac_type,
					create_time: (new Date()).Format("yyyyMMdd")
				}).then(e => {
					_self.requireThickPhotoByMacnumbAndPosnoApi(_self.selectTableData.mac_numb, _self.selectPosNo);
				})
			},

			updateThickListPlanStateApi(inDmgCode, inState) {
				console.log(`$$$$$$===updateThickListPlanStateApi====${inDmgCode} ${inState} `)
				let _self = this;
				updateThickListPlanState(inDmgCode, inState).then(e => {
					uni.showToast({
						title:"更新list plan state",
						icon:"none"
					});
				})
			},

			/**
			 * 更新外部表格里机器的计划标记
			 * plan_mac_numb  计划状态   
				3：双同心圆  作业中
				1：单圆   未实施
				2：实心圆 已实施
				4：未计划
				
				plan_cls_type  计划状态  4：未计划   1：计划但未实施  2：计划完成？ 3：未计划完成
			 */
			checkUpdateThickPlanState() {
				console.log("$$$$$$===checkUpdateThickPlanState====$$$")
				let noPlan = false; // 4
				let noPlanFinish = false; // 3
				let planFinish = false; // 2
				let planNoFinish = false; // 1
				this.tableDataList.forEach(listItem => {
					let tempPlanClsType = Number(listItem.plan_cls_type);
					if (tempPlanClsType == 4)
						noPlan = true;
					else if (tempPlanClsType == 3)
						noPlanFinish = true;
					else if (tempPlanClsType == 2)
						planFinish = true;
					else if (tempPlanClsType == 1)
						planNoFinish = true;
				});

				let tempPlanMacNumb = 4;
				if (noPlan && !noPlanFinish && !planFinish && !planNoFinish) // 4 未计划
					tempPlanMacNumb = 4;
				else if (planNoFinish && (planFinish || planNoFinish)) // 3 作业中
					tempPlanMacNumb = 3;
				else if (!planNoFinish && (noPlanFinish || planFinish) ) // 2 已实施
					tempPlanMacNumb = 2;
				else if ( planNoFinish && !planFinish && !noPlanFinish ) // 1 计划但未实施
					tempPlanMacNumb = 1;
					
				console.log(`$$$$$$===checkUpdateThickPlanState====$$$ ${noPlan} ${noPlanFinish} ${planFinish} ${planNoFinish}`);
				console.log(`$$$$$$===checkUpdateThickPlanState====$$$ ${tempPlanMacNumb}`);
				this.updateThickListPlanStateApi(this.selectTableData.dmg_code, tempPlanMacNumb);
			},

			onResetViewClick() {
				this.$refs.drawingBasicFun.resetDrawView();
			},

			/**
			 * 表格行选中
			 * @param {Object} e
			 */
			onTableSelectionChange(e) {
				this.tableSelectData = e;
				this.selectPosNo = e.pos_no;

				this.requireThickHistoryDataApi();
			},

			/**
			 * 图纸截图完成后 返回截图path
			 * @param {Object} e
			 */
			onDrawShotFinish(e) {
				this.drawShotPath = e;
			},

			/**
			 * 图纸markup被选中选中
			 * @param {Object} e
			 */
			onElementSelect(e) {
				let tempIndex = -1;
				for (let i = 0; i < this.tableDataList.length; i++) {
					if (this.tableDataList[i].pos_no == e.posOrder) {
						tempIndex = i;
						break;
					}
				}
				// this.tableSelectData = this.tableDataList[tempIndex];
				this.selectPosNo = this.tableDataList[tempIndex].pos_no;
				if (tempIndex != -1 && this.showState == "table")
					this.$refs.checkInfoTableView.setSingleSelectDataIndex(tempIndex);
				this.requireThickPhotoByMacnumbAndPosnoApi(this.selectTableData.mac_numb, this.tableDataList[tempIndex]
					.pos_no);
			},

			updateTableShowType() {
				// this.tableHeadData = selectData.checkTableData.headData;
				this.tableHeadData = [];
				let temp = [];
				selectData.checkTableData.headData.forEach(e => {
					if (e.showType.indexOf(this.tableShowType) != -1) {
						if (e.key == "corrvalue" && !getApp().globalData.thickSetting.ChkUseTmprCrct) {
							console.log("updateTableShowType --- jump --- corrvalue")
						} else {
							console.log("updateTableShowType --- " + e.key)
							temp.push(e);
						}
					}
					this.tableHeadData = temp;
				})
			},

			onToolItemClick(e) {
				console.log("onToolItemClick --- ", e)
				if (e == "bill") {
					this.showWildAccountPopup = true;
				} else if (e == "dataentry") {
					console.log("onToolItemClick ---bill ", this.tableSelectData)
					if (this.tableSelectData == null) {
						uni.showToast({
							title: this.$t("warnning.singleSelect"),
							icon: 'none'
						})
						return;
					}

					this.showLogPopup = true;
				} else if (e == "camera") {
					this.showCameraPage();
				} else if (e == "takephoto") {
					this.takePhoto();
				} else if (e == "editphoto") {
					this.editPhoto();
				} else if (e == "switch") {
					this.switchTableShow();
				}
			},

			showCameraPage() {
				if (this.showState == "table") {
					this.showState = "photo";
					this.toolDataList = selectData.photoToolEntry;
				} else {
					this.showState = "table";
					this.toolDataList = selectData.toolEntry;
				}
			},

			closeWildAccountView() {
				this.showWildAccountPopup = false;
			},

			closelogView() {
				this.showLogPopup = false;
				this.requireThickDetailDataApi(this.selectTableData.dmg_code);
			},

			takePhoto() {
				if (this.selectPosNo == -1) {
					uni.showToast({
						title: "not select one"
					})
					return;
				}

				let _self = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["camera", "album"], //从相册选择
					success: function(res) {
						res.tempFilePaths.forEach((e) => {
							console.log(e)
							uni.saveFile({
								tempFilePath: e,
								success: function(saveres) {
									_self.addThickPhotoByMacnumbAndPosnoApi(saveres
										.savedFilePath);
								}
							});
						});
					},
				});
			},

			/**
			 * 编辑图片
			 */
			editPhoto() {
				let tempIndex = this.$refs.photoListView.getSelectImage().index;
				uni.navigateTo({
					url: "/pages/thickness/editPhotos?dataList=" +
						JSON.stringify(this.takePhotoPaths) +
						"&currentIndex=" + tempIndex,
				});
			},

			/**
			 * 更新表格显示样式type 0 1 2
			 */
			switchTableShow() {
				if (this.tableShowType < 2)
					this.tableShowType++;
				else
					this.tableShowType = 0;
				this.updateTableShowType();
			},
			navigateBack() {
				uni.navigateBack();
			},
		},
	};
</script>

<style scoped lang="scss">
	.content-lay {
		// background: #fff;
		width: 100%;
	}

	.hqs-popup {
		height: calc(80vh - var(--status-bar-height));
	}

	.header {
		background-color: #fff;
		box-sizing: border-box;
		padding: 6rpx;
		padding-right: 12rpx;
		align-items: center;
		justify-content: space-between;

		.back-image {
			width: 22rpx;
			height: 22rpx;
		}

		.header-name-lay {
			align-items: center;
			margin-right: 9rpx;

			.header-name {
				margin-left: 6rpx;
				font-size: 14rpx;
				color: #1f2329;
				font-weight: 400;
			}

			.header-value {
				background: #fdfacc;
				border-radius: 1rpx;
				border: 1px solid #cfd3d5;
				padding: 8rpx 12rpx;
				font-weight: 400;
				font-size: 14rpx;
				color: #333333;
			}

			.header-value-oth {
				width: 168upx;
			}
		}
	}

	.work-lay {
		box-sizing: border-box;
		justify-content: space-between;
		width: 100%;
		height: 100%;
		align-items: center;
		padding: 12rpx;

		.left-info-lay {
			width: 20%;
			// width: 155upx;
			height: 100%;
			background-color: #ffffff;
			box-sizing: border-box;
			padding: 12rpx;

			.photo-list {
				height: 100%;
			}
		}

		.right-content-lay {
			box-sizing: border-box;
			width: 80%;
			height: 100%;
			padding-left: 12rpx;
			background-color: #F6F6F6;
		}
	}

	.check-table {
		background-color: #fff;
		margin-top: 9px;
		padding: 12rpx;
		padding-bottom: 0rpx;
		box-sizing: border-box;
	}

	/deep/ .qs-con {
		border-radius: 0 !important;
	}
</style>
